// pages/expressGet/expressGet.js
import WxValidate from "../../utils/WxValidate";
import showValidateModal from "../../utils/showValidateModal";
import utils from "../../utils/util";
const app = getApp();
Page({
  //选择垃圾大小
  chooseType(e) {
    const { index } = e.currentTarget.dataset;
    this.setData({
      currentType: index,
      "form.rubbishType": this.data.trashType[index].name,
      "form.payMoney": this.data.trashType[index].money,
      expressIndex: 0,
    });
  },
  //选择地址
  selectAddress() {
    wx.navigateTo({ url: "../address/address" });
  },
  //免责声明
  showStatment() {
    wx.showModal({
      title: "用户条款&隐私策略",
      content: "这里是隐私条款具体内容",
      showCancel: false,
    });
  },
  /* 路由地址跳转 */
  handleaddress() {
    wx.navigateTo({
      url: "../address/address",
    });
  },
  /* 快递数量 */
  num(e) {
    const value = e.detail.value;
    const NumMon = parseInt(this.data.expressNumArray[value]);
    this.setData({
      expressIndex: value,
      "form.rubbishNum": this.data.expressNumArray[value],
      "form.payMoney":
        NumMon * this.data.trashType[this.data.currentType].money,
    });
  },
  /**
   * 页面的初始数据
   */
  data: {
    trashType: [
      { name: "鞋盒大", money: 1 },
      { name: "椅子大", money: 3 },
      { name: "普通大", money: 5 },
    ],
    expressIndex: 0,
    expressNumArray: ["1个", "2个", "3个", "4个", "5个", "6个"],
    currentType: 0,
    trashIndex: 0,
    form: {
      rubbishType: "鞋盒大", //垃圾大小
      address: "", //取货地点
      img: "", //图片截图
      mark: "", //备注信息
      rubbishNum: "1个", //垃圾数量
      payMoney: 1, //支付金额，初始2元
    },
  },
  //保存表单
  async submitForm() {
    //判断当前用户是否已授权登录
    const r = await showValidateModal.cklogin(app.globalData.userInfo);
    if (!r) {
      return false;
    } //开始对地址 商家选择进行 检测
    const {
      rubbishType,
      address,
      img,
      mark,
      rubbishNum,
      payMoney,
    } = this.data.form;
    const params = { address };
    if (!this.WxValidate.checkForm(params)) {
      const errors = this.WxValidate.errorList[0];
      showValidateModal.showValidateModal(errors);
      return false;
    } //检查 取件信息
    if (!img && !mark) {
      wx.showModal({
        title: "提示",
        content: "请输入备注信息或上传截图",
        showCancel: false,
      });
      return false;
    }
    //保存数据库
    const publicTime = utils.formatTime(new Date());
    wx.showLoading({});
    wx.request({
      url: `${app.globalData.server}/addOrder`,
      method: "POST",
      data: {
        openid: app.globalData.userInfo.openid,
        orderType: "代扔垃圾",
        endAddress: "垃圾场",
        startAddress: address,
        payMoney,
        status: "待帮助",
        completed: "未完成",
        publicTime,
        isCompleted: true,
        info: { rubbishType, img, mark, rubbishNum },
        userInfo: app.globalData.userInfo,
      },
      success: (res) => {
        wx.hideLoading({});
        if (res.data == "success") {
          wx.showToast({ title: "提交成功", icon: "success" });
          setTimeout(() => {
            wx.switchTab({ url: "../order/order" });
          }, 1000);
        } else {
          wx.hideLoading({});
          wx.showToast({ title: "发布失败", icon: "error" });
        }
      },
      fail: (err) => {
        wx.hideLoading({});
        wx.showToast({ title: "发布失败", icon: "error" });
      },
    });
  },
  //备注信息
  timeID: 0, //定时器ID
  handleInput(e) {
    const { value } = e.detail;
    clearTimeout(this.timeID); //清楚timeID对应的定时器，即取消相应函数的执行
    this.timeID = setTimeout(() => {
      this.setData({ "form.mark": value });
    }, 500);
  },
  //取件信息 上传图片
  uploadImg() {
    //调用wx.chooseMedia API打开图片选择窗口
    wx.chooseMedia({
      count: 1,
      mediaType: ["image"],
      sourceType: ["album", "camera"],
      sizeType: ["original", "compressed"],
      success: (res) => {
        //chooseMedia成功回调
        wx.showLoading({ title: "上传中" });
        //使用wx.uploadFile将图片发至服务端上传
        wx.uploadFile({
          filePath: res.tempFiles[0].tempFilePath,
          //文件暂存路径
          name: "img", //文件对应的 key
          url: `${app.globalData.server}/uploadImg`, //服务端路由
          success: (result) => {
            //成功回调 //result.data为字符串，使用JSON.parse转成对象
            let filePath = JSON.parse(result.data).path; //文件路径为\反斜杠，需要转为斜杠/，使用正则表达式进行过滤转换
            filePath = filePath.replace(/\\/g, "/");
            let form = this.data.form; //将完整的文件路径（含有域名信息）赋值给userInfo
            form.img = `${app.globalData.server}/${filePath}`;
            this.setData({ form });
            wx.hideLoading({});
            wx.showToast({ title: "上传成功", icon: "success" });
          },
          fail: (e) => {
            //失败回调 console.log(e)
            wx.hideLoading({});
            wx.showToast({ title: "上传失败", icon: "error" });
          },
        });
      },
      fail: (error) => {
        //chooseMedia失败回调 console.log(error)
        wx.showToast({ title: "上传失败", icon: "error" });
      },
    });
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    this.initValidate();
  },
  initValidate() {
    // 验证字段的规则
    const rules = { address: { required: true } }; // 验证字段的提示信息，若不传则调用默认的信息
    const messages = { address: { required: "请选择地址" } };
    // 创建实例对象
    this.WxValidate = new WxValidate(rules, messages);
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {},

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {},

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {},

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {},

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {},

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {},

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {},
});
